package com.android.tiango.baba.act;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaBaseActivity;
import com.android.tiango.baba.adapter.ChildPostAdapter;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.entity.IndexHotTopicsEntity;
import com.android.tiango.baba.entity.SimpleTopicModel;
import com.android.tiango.baba.entity.SimpleUserModel;
import com.android.tiango.baba.entity.UserModel;
import com.android.tiango.baba.util.Constants;
import com.android.tiango.baba.util.ImageLoader;
import com.android.tiango.baba.util.StringUtils;
import com.android.tiango.baba.util.TimeToUtil;
import com.android.tiango.baba.view.AppTitleBar;
import com.android.tiango.baba.view.MeasureListView;
import com.android.tiango.baba.view.PullListView;
import com.android.tiango.baba.view.PullListView.PullListViewListener;

/**
 * 我的帖子
 * 
 * @author txg
 * 
 */
public class ActPosts extends BaBaseActivity implements PullListViewListener,
		OnClickListener {
	protected PullListView mListView, mListView2;
	private ListAdapter mAdapter;
	private Button mBtnActPost, mBtnTopicPost;
	private ArrayList<String> mDate = new ArrayList<String>();
	private ParticAdapter mAdapter2;
	private final int REQTYPE = 0;
	private final int REQPARTYPE = 1;
	private int mPageIndex = 0;
	private int mPageIndex_Topic = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_myzoe_posts);
		findView();
	}

	private void findView() {
		mImageLoader=new ImageLoader(this, R.drawable.ic_default);
		mTitleBar = (AppTitleBar) findViewById(R.id.titlebar);
		if (null != mTitleBar) {
			mTitleBar.setTitle(getString(R.string.sMytopic));
			mTitleBar.setImageBackGround(R.drawable.bg_title_blue);
			mTitleBar.setBackIcon(R.drawable.icon_back);
			// mTitleBar.setMoreIcon(R.drawable.icon_collect);
			setBackOnClickListener();
		}
		// button
		mBtnActPost = (Button) findViewById(R.id.btnactpost);
		mBtnTopicPost = (Button) findViewById(R.id.btntopicpost);
		mBtnActPost.setOnClickListener(this);
		mBtnTopicPost.setOnClickListener(this);
		mBtnActPost.setText(getString(R.string.s_mypost));
		mBtnTopicPost.setText(getString(R.string.s_mypar));
		// listview
		mListView = (PullListView) findViewById(R.id.id_pull_listview);
		mListView.setHeaderDividersEnabled(false);
		mListView.setFooterDividersEnabled(false);
		mListView.setSelector(android.R.color.transparent);
		mListView.setPullListener(this);
		mAdapter = new ListAdapter();
		mListView.setAdapter(mAdapter);
		mListView.startOnRefresh();
		// listview2
		mListView2 = (PullListView) findViewById(R.id.id_pull_listview_par);
		mListView2.setHeaderDividersEnabled(false);
		mListView2.setFooterDividersEnabled(false);
		mListView2.setSelector(android.R.color.transparent);
		//

	}

	@Override
	public void onPullRefresh() {
		mPageIndex = 1;
		doDate(REQTYPE);
	}

	@Override
	public void onPullLoadMore() {
		mPageIndex += 1;
		doDate(REQTYPE);
	}

	// 我的发帖集合
	private class ListAdapter extends BaseAdapter {
		private ArrayList<ArrayList<SimpleTopicModel>> mDate;

		public ListAdapter() {
			if (mDate == null) {
				mDate = new ArrayList<ArrayList<SimpleTopicModel>>();
			}
		}

		public void setData(ArrayList<ArrayList<SimpleTopicModel>> mDate) {
			this.mDate = mDate;
		}

		@Override
		public int getCount() {
			return mDate.size();
		}

		@Override
		public ArrayList<SimpleTopicModel> getItem(int position) {
			return mDate.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ItemTag tag;
			if (convertView == null) {
				tag = new ItemTag();
				convertView = LayoutInflater.from(ActPosts.this).inflate(
						R.layout.item_myposts, null);
				tag.tv_partitle = (TextView) convertView .findViewById(R.id.tv_partitle);
				tag.listView = (MeasureListView) convertView .findViewById(R.id.ml_listview);
				convertView.setTag(tag);
			} else {
				tag = (ItemTag) convertView.getTag();
			} 
			
			ArrayList<SimpleTopicModel> barData = getItem(position);
			if (barData != null) {
				tag.tv_partitle.setText(barData.get(0).getBarName());
				tag.listView.setAdapter(new ChildPostAdapter(barData, ActPosts.this));
//				convertView.setOnClickListener(new OnClickListener() {
//					@Override
//					public void onClick(View v) {
//						
//					}
//				});
			}
			return convertView;
		}

		class ItemTag {
			TextView tv_partitle;
			MeasureListView listView;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnactpost:
			// 我的发贴
			mBtnActPost.setBackgroundResource(R.drawable.bg_toptitlebtn);
			mBtnTopicPost
					.setBackgroundResource(R.drawable.bg_toptitlebtn_pressed);
			mListView.setVisibility(View.VISIBLE);
			mListView2.setVisibility(View.GONE);
			if (mAdapter != null && mDate != null) {
				mAdapter.notifyDataSetChanged();
			} else {
				mListView.startOnRefresh();
			}
			break;
		case R.id.btntopicpost:
			// button
			mBtnTopicPost.setBackgroundResource(R.drawable.bg_toptitlebtn_left);
			mBtnActPost
					.setBackgroundResource(R.drawable.bg_toptitlebtn_pressed_left);
			// listview2
			mListView.setVisibility(View.GONE);
			mListView2.setVisibility(View.VISIBLE);
			if (mAdapter2 == null) {

				mListView2.setPullListener(new PullListViewListener() {
					@Override
					public void onPullRefresh() {
						mPageIndex_Topic = 1;
						doDate(REQPARTYPE);
					}

					@Override
					public void onPullLoadMore() {
						mPageIndex_Topic += 1;
						doDate(REQPARTYPE);
					}
				});
				mAdapter2 = new ParticAdapter();
				mListView2.setAdapter(mAdapter2);
				mListView2.startOnRefresh();

			} else {
				mAdapter2.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}
	}

	// 我参与的
	class ParticAdapter extends BaseAdapter {
		private ArrayList<SimpleTopicModel> mDate;

		public ParticAdapter() {
			if (mDate == null) {
				mDate = new ArrayList<SimpleTopicModel>();
			}
		}

		public void setData(ArrayList<SimpleTopicModel> mDate) {
			this.mDate = mDate;
		}

		@Override
		public int getCount() {
			return mDate.size();
		}

		@Override
		public SimpleTopicModel getItem(int position) {
			return mDate.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ItemTag tag;
			if (convertView == null) {
				tag = new ItemTag();
				convertView = LayoutInflater.from(ActPosts.this).inflate(
						R.layout.item_myposts_par, null);
				tag.tv_partitle = (TextView) convertView .findViewById(R.id.tv_partitle);
				tag.iv_parhead = (ImageView) convertView .findViewById(R.id.iv_parhead);
				tag.tv_parname = (TextView) convertView .findViewById(R.id.tv_parname);
				tag.tv_pardata = (TextView) convertView.findViewById(R.id.tv_pardata);
				tag.iv_sex = (ImageView) convertView.findViewById(R.id.iv_sex);
				tag.tv_replay = (TextView) convertView.findViewById(R.id.tv_replay);
				tag.tv_postinfo = (TextView) convertView.findViewById(R.id.tv_postinfo);
				// tag.tv_actinfo = (TextView)
				// convertView.findViewById(R.id.tv_actinfo);
				convertView.setTag(tag);
			} else {
				tag = (ItemTag) convertView.getTag();
			}
			SimpleTopicModel model = getItem(position);
			if (model != null) {
				SimpleUserModel userm = model.getSimpleUser();
				if (userm != null) {
					tag.tv_parname.setText(userm.getNickName());// 用户名
					mImageLoader.loadImage(userm.getAvatarUrl(), tag.iv_parhead);// 头像
					int gender = userm.getGender();// 性别
					if (gender == 1) {
						tag.iv_sex.setImageDrawable(getResources().getDrawable(
								R.drawable.bg_sex));
					} else if (gender == 2) {
						tag.iv_sex.setImageDrawable(getResources().getDrawable(
								R.drawable.bg_sex_girl));
					}
				}
				tag.tv_partitle.setText(model.getBarName());// 吧
				tag.tv_pardata.setText(TimeToUtil.getSystemTimeSetFormat(
						model.getCreateTime(), TimeToUtil.ACCURATE_TO_THE_DAY));// 时间
				tag.tv_replay.setText(model.getReplyContent());
				tag.tv_postinfo.setText(model.getReplyContent());
				convertView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {

					}
				});
			}
			return convertView;
		}

		private class ItemTag {
			TextView tv_partitle;
			ImageView iv_parhead;
			TextView tv_parname;
			TextView tv_pardata;
			ImageView iv_sex;
			TextView tv_replay;
			TextView tv_postinfo;
		}

	}

	private void doDate(final int type) {
		UserModel model = ShareCookie.getUserInfo();
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpParams = new HttpParams();
		httpParams.put("token", model.getToken());
		httpParams.put("type", type);
		if (type == REQTYPE) {
			httpParams.put("pageIndex", mPageIndex);
		} else {
			httpParams.put("pageIndex", mPageIndex_Topic);
		}
		httpParams.put("pageSize", Constants.PAGE_SIZE);
		// 0-我发布的帖子 1-我参与的帖子
		client.get(HttpUrl.getUrl(HttpUrl.MYTOPICS), httpParams,new HttpCallBack() {
					public void onHttpFailure(Exception arg0, String arg1) {
						if (!StringUtils.isEmpty(arg1)) {
							Toast.makeText(ActPosts.this, arg1, Toast.LENGTH_LONG).show();
						}
						
						if (mListView.getVisibility() == View.VISIBLE) {
							mListView.onRefreshFinish();
							mListView.onLoadFinish();
							mPageIndex = mPageIndex > 1 ? mPageIndex--  : mPageIndex ;
						} else if (mListView2.getVisibility() == View.VISIBLE) {
							mListView2.onRefreshFinish();
							mListView2.onLoadFinish();
							mPageIndex_Topic = mPageIndex_Topic > 1 ? mPageIndex_Topic--  : mPageIndex_Topic ;
							
						} 
					}

					public void onHttpStarted() {}
					
					/**
					 * 测试数据
					private ArrayList<SimpleTopicModel> test() {
						ArrayList<SimpleTopicModel> list = new ArrayList<SimpleTopicModel>();
						for (int i = 0; i < 10; i++) {
							int index = (int) (Math.random() * 10);
							SimpleTopicModel model = new SimpleTopicModel();
							model.setBarId(index + "");
							model.setBarName("吧::" + index);
							model.setTopicName("帖子测试：" + i);
							list.add(model);
							System.out.println("" + model.getBarName());
						}
						return list;
					}*/

					public void onHttpSuccess(Object arg0) {
						IndexHotTopicsEntity entity = (IndexHotTopicsEntity) arg0;
						ArrayList<SimpleTopicModel> data = entity.getData();
						if (data != null && data.size() > 0) {
							if (type == 0) {
								ArrayList<ArrayList<SimpleTopicModel>> barData = sortDate(data);
								// 0-我发布的帖子
								if (mAdapter == null) {
									mAdapter = new ListAdapter();
									mAdapter.setData(barData);
									mListView.setAdapter(mAdapter);
								} else {
									mAdapter.setData(barData);
									mAdapter.notifyDataSetChanged();
								}
								mListView.onRefreshFinish();
								mListView.onLoadFinish();
							} else if (type == 1) {
								// 1-我参与的帖子
								if (mAdapter2 == null) {
									mAdapter2 = new ParticAdapter();
									mAdapter2.setData(data);
									mListView2.setAdapter(mAdapter2);
								} else {
									mAdapter2.setData(data);
									mAdapter2.notifyDataSetChanged();
								}
								mListView2.onRefreshFinish();
								mListView2.onLoadFinish();
							}
						} else {
							mListView.onRefreshFinish();
							mListView.onLoadFinish();
							mListView2.onRefreshFinish();
							mListView2.onLoadFinish();
							Toast.makeText(ActPosts.this, R.string.s_notdata,
									Toast.LENGTH_LONG).show();
						}
					}
				}, IndexHotTopicsEntity.class);
	}

	class MyComparator implements Comparator<SimpleTopicModel> {
		public int compare(SimpleTopicModel s1, SimpleTopicModel s2) { 
			// 根据吧ID区分是否帖子同属于一个吧
			if (s1.getBarId().endsWith(s2.getBarId())) {
				return 1;
			}else if(s1.getBarName()==null || s2.getBarName()==null){ 
				return -1;
			}
			return 0;
		}

	}

	/**
	 * 数据排序
	 * 
	 * @param data
	 *            原“我的发帖”数据信息
	 * @return ArrayList<ArrayList<SimpleTopicModel>>
	 */
	private ArrayList<ArrayList<SimpleTopicModel>> sortDate(
			ArrayList<SimpleTopicModel> data) {
		Comparator comparator = new MyComparator();
		Collections.sort(data, comparator);
		ArrayList<ArrayList<SimpleTopicModel>> datas = new ArrayList<ArrayList<SimpleTopicModel>>();
		ArrayList<SimpleTopicModel> bar = null;// 一个吧
		for (int i = 0; i < data.size(); i++) {
			SimpleTopicModel simplel = data.get(i);
			if (i != 0 && i < data.size()) {
				SimpleTopicModel simple2 = data.get(i - 1);
				if (simplel.getBarId().equals(simple2.getBarId())) {
					bar.add(simplel);

				} else {
					datas.add(bar);
					bar = new ArrayList<SimpleTopicModel>();
					bar.add(simplel);
				}
				if (i + 1 == data.size()) {
					datas.add(bar);
				}
			} else {
				bar = new ArrayList<SimpleTopicModel>();
				bar.add(simplel);
			}
		}

		return datas;
	}
}